<template>
  <div class="table-data-container">
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>数据管理 - {{ tableName }}</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增数据
            </el-button>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>导出
            </el-button>
            <el-button type="warning" @click="handleGenerateData">
              <el-icon><Star /></el-icon>生成测试数据
            </el-button>
            <el-button type="danger" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="table-wrapper">
        <el-table 
          :data="tableData" 
          style="width: 100%"
          v-loading="loading"
          border
          size="default"
          table-layout="auto"
        >
          <!-- 动态生成所有列 -->
          <el-table-column 
            v-for="column in tableColumns"
            :key="column"
            :prop="column"
            :label="column"
            :min-width="getColumnWidth(column)"
            show-overflow-tooltip
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <div 
                class="cell-content"
                @click="handleCellClick(scope.row, column)"
              >
                {{ formatCellValue(scope.row[column]) }}
              </div>
            </template>
          </el-table-column>
          
          <!-- 添加操作列 -->
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
                :icon="Delete"
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            :pager-count="7"
            background
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :popper-props="{
              popperClass: 'custom-pagination-dropdown'
            }"
          >
            <template #total>
              共 <span style="color: var(--el-color-primary)">{{ pagination.total }}</span> 条
            </template>
            <template #sizes="{ handleSizeChange: _ }">
              <span style="margin-right: 8px">每页</span>
              <el-select
                v-model="pagination.size"
                @change="handleSizeChange"
                style="width: 100px"
              >
                <el-option
                  v-for="item in [10, 20, 50, 100]"
                  :key="item"
                  :value="item"
                  :label="item + ' 条'"
                />
              </el-select>
            </template>
            <template #jumper>
              前往 <el-input
                v-model.number="pagination.current"
                style="width: 50px; margin: 0 8px"
                @change="(val) => handleCurrentChange(val || 1)"
              /> 页
            </template>
          </el-pagination>
        </div>
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
        v-model="editDialogVisible"
        :title="'编辑数据'"
        width="60%"
        :close-on-click-modal="false"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editRules"
          label-width="100px"
        >
          <el-form-item :label="editForm.columnName" prop="value">
            <template v-if="editForm.columnType === 'varchar' || editForm.columnType === 'text'">
              <el-input 
                v-if="!isLongText(editForm.value)"
                v-model="editForm.value"
                :placeholder="'请输入' + editForm.columnName"
              />
              <el-input 
                v-else
                v-model="editForm.value"
                type="textarea"
                :rows="10"
                :placeholder="'请输入' + editForm.columnName"
                resize="both"
              />
            </template>
            <el-input-number 
              v-else-if="['bigserial', 'int8', 'int4', 'int2'].includes(editForm.columnType)"
              v-model="editForm.value"
              :placeholder="'请输入' + editForm.columnName"
              :precision="0"
            />
            <el-input-number 
              v-else-if="editForm.columnType === 'numeric'"
              v-model="editForm.value"
              :placeholder="'请输入' + editForm.columnName"
              :precision="2"
            />
            <el-date-picker
              v-else-if="editForm.columnType === 'timestamp'"
              v-model="editForm.value"
              type="datetime"
              :placeholder="'请选择' + editForm.columnName"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
            <el-input 
              v-else
              v-model="editForm.value"
              :placeholder="'请输入' + editForm.columnName"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveEdit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 新增数据对话框 -->
      <el-dialog
        v-model="addDialogVisible"
        title="新增数据"
        width="60%"
        :close-on-click-modal="false"
      >
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addRules"
          label-width="120px"
        >
          <el-form-item 
            v-for="column in tableColumns.filter(col => col !== 'id')"
            :key="column"
            :label="column"
            :prop="column"
          >
            <template v-if="columnTypes[column] === 'varchar' || columnTypes[column] === 'text'">
              <el-input 
                v-model="addForm[column]"
                :placeholder="'请输入' + column"
                :type="isLongText(addForm[column]) ? 'textarea' : 'text'"
                :rows="isLongText(addForm[column]) ? 4 : 1"
              />
            </template>
            <el-input-number 
              v-else-if="['bigserial', 'int8', 'int4', 'int2'].includes(columnTypes[column])"
              v-model="addForm[column]"
              :placeholder="'请输入' + column"
              :precision="0"
            />
            <el-input-number 
              v-else-if="columnTypes[column] === 'numeric'"
              v-model="addForm[column]"
              :placeholder="'请输入' + column"
              :precision="2"
            />
            <el-date-picker
              v-else-if="columnTypes[column] === 'timestamp'"
              v-model="addForm[column]"
              type="datetime"
              :placeholder="'请选择' + column"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
            <el-input 
              v-else
              v-model="addForm[column]"
              :placeholder="'请输入' + column"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveAdd">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Refresh, Plus, Download, Star, Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const loading = ref(false)
const tableData = ref([])
const tableColumns = ref([])
const tableName = ref('')

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 编辑相关的响应式变量
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  columnName: '',
  columnType: '',
  value: null,
  columnId: null,
  tableName: ''
})

const editRules = {
  value: [
    { required: true, message: '请输入数据', trigger: 'blur' }
  ]
}

// 新增相关的响应式变量
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({})
const columnTypes = reactive({})
const addRules = reactive({})

// 获取表数据
const fetchTableData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/connection/tableData', {
      params: {
        connectionId: route.query.connectionId,
        tableName: route.query.tableName,
        current: pagination.current,
        size: pagination.size
      }
    })
    if (response.data.code === '200') {
      tableData.value = response.data.data.records || []
      tableColumns.value = response.data.data.columns || []
      pagination.total = response.data.data.total || 0
      pagination.current = response.data.data.current || 1
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1 // 切换每页条数时重置为第一页
  fetchTableData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.current = val
  fetchTableData()
}

const handleRefresh = () => {
  fetchTableData()
}

// 根据列名设置合适的列宽
const getColumnWidth = (column) => {
  // 日期时间类型的列
  if (column.includes('time') || column.includes('date')) {
    return 200
  }
  // ID类型的列
  if (column.includes('id') || column === 'id') {
    return 150
  }
  // 状态类型的列
  if (column.includes('status') || column.includes('type')) {
    return 120
  }
  // 金额类型的列
  if (column.includes('fee') || column.includes('amount') || column.includes('coverage')) {
    return 180
  }
  // 名称类型的列
  if (column.includes('name')) {
    return 180
  }
  // 默认列宽
  return 160
}

// 获取字段类型
const getColumnType = async (columnName) => {
  try {
    const response = await axios.get(`/api/connection/${route.query.connectionId}/tableDataType`, {
      params: {
        tableName: route.query.tableName,
        columnName: columnName
      }
    })
    
    if (response.data.code === '200') {
      return response.data.data
    } else {
      ElMessage.error(response.data.message || '获取字段类型失败')
      return null
    }
  } catch (error) {
    console.error('获取字段类型失败:', error)
    ElMessage.error(error.response?.data?.message || '获取字段类型失败')
    return null
  }
}

// 处理单元格点击
const handleCellClick = async (row, column) => {
  console.log('单元格被点击:', row, column)
  // 如果是id列，不允许编辑
  if (column === 'id') {
    return
  }

  try {
    const response = await axios.get(`/api/connection/${route.query.connectionId}/tableDataType`, {
      params: {
        tableName: route.query.tableName,
        columnName: column
      }
    })
    
    if (response.data.code === '200') {
      console.log('获取到的字段类型:', response.data.data)
      editForm.columnName = column
      editForm.columnType = response.data.data
      editForm.value = row[column]
      editForm.columnId = row.id
      editForm.tableName = route.query.tableName
      console.log('设置editForm:', editForm)

      editDialogVisible.value = true
    } else {
      ElMessage.error(response.data.message || '获取字段类型失败')
    }
  } catch (error) {
    console.error('处理单元格点击失败:', error)
    ElMessage.error(error.response?.data?.message || '处理单元格点击失败')
  }
}

// 定义保存编辑的方法
const handleSaveEdit = async () => {
  console.log('handleSaveEdit 被调用')
  console.log('当前 editForm:', editForm)
  
  if (!editFormRef.value) {
    console.log('editFormRef.value 为空')
    return
  }

  try {
    await editFormRef.value.validate()
    
    let columnValue = editForm.value
    if (columnValue === null || columnValue === undefined) {
      columnValue = ''
    } else {
      columnValue = columnValue.toString()
    }
    console.log('初始 columnValue:', columnValue)
    
    // 如果是时间戳类型，强制转换为YYYY-MM-DD HH:mm:ss格式
    if (editForm.columnType === 'timestamp' && editForm.value) {
      console.log('处理时间戳类型，原始值:', editForm.value)
      try {
        // 将日期字符串转换为Date对象
        const date = new Date(editForm.value)
        if (isNaN(date.getTime())) {
          throw new Error('无效的日期格式')
        }
        // 格式化为YYYY-MM-DD HH:mm:ss
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        columnValue = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        console.log('转换后的时间格式:', columnValue)
      } catch (error) {
        console.error('日期转换失败:', error)
        ElMessage.error('日期格式无效')
        return
      }
    }
    
    const requestData = {
      tableName: editForm.tableName,
      columnName: editForm.columnName,
      columnType: editForm.columnType,
      columnId: editForm.columnId,
      columnValue: columnValue
    }
    console.log('发送到后端的数据:', requestData)
    
    const response = await axios.put(`/api/connection/${route.query.connectionId}/UpdateTableData`, requestData)

    if (response.data.code === '200') {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      // 刷新数据
      fetchTableData()
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    console.error('保存编辑失败:', error)
    ElMessage.error(error.response?.data?.message || '保存失败')
  }
}

// 判断是否为长文本
const isLongText = (text) => {
  return text && text.length > 100
}

// 在表格中显示时截断长文本
const formatCellValue = (value) => {
  if (typeof value === 'string' && value.length > 50) {
    return value.substring(0, 50) + '...'
  }
  return value
}

// 获取所有字段的类型
const fetchColumnTypes = async () => {
  try {
    const promises = tableColumns.value
      .filter(col => col !== 'id')
      .map(async column => {
        const response = await axios.get(`/api/connection/${route.query.connectionId}/tableDataType`, {
          params: {
            tableName: route.query.tableName,
            columnName: column
          }
        })
        if (response.data.code === '200') {
          columnTypes[column] = response.data.data
          // 设置验证规则
          addRules[column] = [
            { required: true, message: `请输入${column}`, trigger: 'blur' }
          ]
        }
      })
    await Promise.all(promises)
  } catch (error) {
    console.error('获取字段类型失败:', error)
    ElMessage.error('获取字段类型失败')
  }
}

// 添加导出功能
const handleExport = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/connection/tableData', {
      params: {
        connectionId: route.query.connectionId,
        tableName: route.query.tableName,
        current: 1,
        size: 1000, // 导出更多数据
        export: 1
      },
      responseType: 'blob'
    })

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    const filename = `${route.query.tableName}_${new Date().toISOString().split('T')[0]}`
    link.setAttribute('download', `${filename}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 添加生成测试数据的方法
const handleGenerateData = () => {
  ElMessageBox.prompt('请输入要生成的数据条数', '生成测试数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[1-9]\d*$/,
    inputErrorMessage: '请输入正整数',
    inputValue: '10'
  }).then(({ value }) => {
    generateData(parseInt(value))
  }).catch(() => {})
}

const generateData = async (n) => {
  try {
    loading.value = true
    const response = await axios.get(`/api/connection/${route.query.connectionId}/generateData`, {
      params: {
        tableName: route.query.tableName,
        n: n
      }
    })

    if (response.data.code === '200') {
      ElMessage.success(response.data.message || '生成数据成功')
      // 刷新表格数据
      fetchTableData()
    } else {
      ElMessage.error(response.data.message || '生成数据失败')
    }
  } catch (error) {
    console.error('生成数据失败:', error)
    ElMessage.error(error.response?.data?.message || '生成数据失败')
  } finally {
    loading.value = false
  }
}

// 删除单条数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除ID为 ${row.id} 的数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.delete(
        `/api/connection/${route.query.connectionId}/${route.query.tableName}/${row.id}/delete`
      )
      if (response.data.code === '200') {
        ElMessage.success('删除成功')
        fetchTableData()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 批量删除数据
const handleBatchDelete = () => {
  ElMessageBox.prompt(
    '请输入要删除的ID范围（例如：1-100）',
    '批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+-\d+$/,
      inputErrorMessage: '请输入正确的格式，例如：1-100'
    }
  ).then(async ({ value }) => {
    const [start, end] = value.split('-').map(Number)
    if (start > end) {
      ElMessage.error('起始ID不能大于结束ID')
      return
    }
    
    try {
      const response = await axios.get(
        `/api/connection/${route.query.connectionId}/${route.query.tableName}/deleteData`, 
        {
          params: {
            start,
            end
          }
        }
      )
      
      if (response.data.code === '200') {
        ElMessage.success(`成功删除ID从 ${start} 到 ${end} 的数据`)
        fetchTableData()
      } else {
        ElMessage.error(response.data.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error(error.response?.data?.message || '批量删除失败')
    }
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(async () => {
  console.log('页面加载，开始获取数据')
  tableName.value = route.query.tableName
  await fetchTableData()
  await fetchColumnTypes()
})
</script>

<style scoped>
/* ... rest of your styles ... */
</style>